<template>
  <div class="pie-chart">
    <div :id="chartId" class="pie-charts"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, onUnmounted } from 'vue';
import {
  SciChartPieSurface,
  EPieType,
  SciChartJsNavyTheme,
  PieSegment,
  ELegendPlacement,
  ELegendOrientation,
  GradientParams,
  Point,
} from 'scichart';

interface SciChartProps {
  data: { labels: string[]; values: number[] };
  colors?: string[];
}

const props = withDefaults(defineProps<SciChartProps>(), {
  colors: () => ['#1F77B4', '#FF7F0E', '#2CA02C', '#D62728', '#9467BD'], // 默认颜色
});

const chartId = ref('pie-chart-' + Math.random().toString(36).substring(2, 9));
const chartInitializationPromise = ref<Promise<any> | undefined>(undefined);

const initSciChart = async () => {
  const sciChartPieSurface = await SciChartPieSurface.create(chartId.value, {
    theme: new SciChartJsNavyTheme(),
    pieType: EPieType.Pie,
    animate: true,
  });

  // Additional legend options
  sciChartPieSurface.legend.showLegend = true;
  sciChartPieSurface.legend.showCheckboxes = true;
  sciChartPieSurface.legend.animate = true;
  sciChartPieSurface.legend.placement = ELegendPlacement.TopRight;
  sciChartPieSurface.legend.orientation = ELegendOrientation.Vertical;

  // Create pie segments with value, colour and text
  const pieSegment1 = new PieSegment({
    color: '#228B22',
    value: 40,
    text: 'Green',
    colorLinearGradient: new GradientParams(new Point(0, 0), new Point(0, 1), [
      { color: '#1D976C', offset: 0 },
      { color: '#93F9B9', offset: 1 },
    ]),
  });
  const pieSegment2 = new PieSegment({
    value: 10,
    text: 'Red',
    colorLinearGradient: new GradientParams(new Point(0, 0), new Point(0, 1), [
      { color: '#DD5E89', offset: 0 },
      { color: '#F7BB97', offset: 1 },
    ]),
  });
  const pieSegment3 = new PieSegment({
    value: 20,
    text: 'Blue',
    colorLinearGradient: new GradientParams(new Point(0, 0), new Point(0, 1), [
      { color: '#1FA2FF', offset: 0 },
      { color: '#12D8FA', offset: 0.5 },
      { color: '#A6FFCB', offset: 1 },
    ]),
  });
  const pieSegment4 = new PieSegment({
    value: 15,
    text: 'Yellow',
    colorLinearGradient: new GradientParams(new Point(0, 0), new Point(0, 1), [
      { color: '#F09819', offset: 0 },
      { color: '#EDDE5D', offset: 1 },
    ]),
  });
  sciChartPieSurface.pieSegments.add(pieSegment1, pieSegment2, pieSegment3, pieSegment4);

  return sciChartPieSurface;
};

onMounted(() => {
  chartInitializationPromise.value = initSciChart();
});

onUnmounted(() => {
  if (chartInitializationPromise.value) {
    chartInitializationPromise.value.then(sciChartSurface => {
      sciChartSurface.delete();
    });
  }
});
</script>

<style lang="scss" scoped>
.pie-chart {
  width: 100%;
  height: 100%;
  .pie-charts {
    width: 100%;
    height: 100%;
  }
}
</style>
